#include "../Engine.h"

namespace Poor3D
{
#include "nedmalloc.c"
}

#include "MemoryPool.h"
Poor3D::MemoryPool gMemoryPool;
#if MEMORY_LEAK_DETECT == 1
#include "MemoryLeakDetect.h"
Poor3D::MemoryLeakDetect gMemoryLeakDetect;
#endif


#if MEMORY_MANAGER_ENABLE
#undef new

// new
inline void* operator new( size_t size )
{
    void* ptr;

#if MEMORY_ALIGN_SIZE == 0
    ptr = gMemoryPool.Malloc( size );
#else
    ptr = gMemoryPool.MallocAligned( size );
#endif

#if MEMORY_LEAK_DETECT == 1
    if ( ptr )
        gMemoryLeakDetect.RecordMalloc( ptr, size );
#endif

    return ptr;
}

inline void* operator new( size_t size, const char* file, int line, const char* func )
{
    void* ptr;

#if MEMORY_ALIGN_SIZE == 0
    ptr = gMemoryPool.Malloc( size );
#else
    ptr = gMemoryPool.MallocAligned( size );
#endif

#if MEMORY_LEAK_DETECT == 1
    if ( ptr )
        gMemoryLeakDetect.RecordMalloc( ptr, size, file, line, func );
#endif

    return ptr;
}

// new[]
inline void* operator new[]( size_t size )
{
    void* ptr;

#if MEMORY_ALIGN_SIZE == 0
    ptr = gMemoryPool.Malloc( size );
#else
    ptr = gMemoryPool.MallocAligned( size );
#endif

#if MEMORY_LEAK_DETECT == 1
    if ( ptr )
        gMemoryLeakDetect.RecordMalloc( ptr, size );
#endif

    return ptr;
}

inline void* operator new[]( size_t size, const char* file, int line, const char* func )
{
    void* ptr;

#if MEMORY_ALIGN_SIZE == 0
    ptr = gMemoryPool.Malloc( size );
#else
    ptr = gMemoryPool.MallocAligned( size );
#endif

#if MEMORY_LEAK_DETECT == 1
    if ( ptr )
        gMemoryLeakDetect.RecordMalloc( ptr, size, file, line, func );
#endif

    return ptr;
}

// delete
inline void operator delete( void* ptr )
{
    gMemoryPool.Free( ptr );

#if MEMORY_LEAK_DETECT == 1
    if ( ptr )
        gMemoryLeakDetect.RecordFree( ptr );
#endif
}

inline void operator delete( void* ptr, const char*, int, const char* )
{
    gMemoryPool.Free( ptr );

#if MEMORY_LEAK_DETECT == 1
    if ( ptr )
        gMemoryLeakDetect.RecordFree( ptr );
#endif
}

// delete[]
inline void operator delete[]( void* ptr )
{
    gMemoryPool.Free( ptr );

#if MEMORY_LEAK_DETECT == 1
    if ( ptr )
        gMemoryLeakDetect.RecordFree( ptr );
#endif
}

inline void operator delete[]( void* ptr, const char*, int, const char* )
{
    gMemoryPool.Free( ptr );

#if MEMORY_LEAK_DETECT == 1
    if ( ptr )
        gMemoryLeakDetect.RecordFree( ptr );
#endif
}

#endif
